package com.liarjo.mywebsiteapi.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.liarjo.mywebsiteapi.util.JwtUtil;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String token = request.getAttribute("token").toString();
        Claims claims = jwtUtil.parseToken(token);
        Long userId = Long.parseLong(claims.getSubject());
        String role = claims.get("role", String.class);;

        // 判断userId是否为admin（这里需要根据你的实际情况来判断）
        if (userId != null && role.equals("admin")) {
            return true; // 如果是admin，允许访问
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized: Only admin can access this resource.");
            return false; // 否则拒绝访问
        }
    }
}
